from requests.packages.urllib3.exceptions import InsecureRequestWarning

# !usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author: lenovo by amidoufu
@file: amidoufu.py
@time: 2020/05/06
@function: 
"""
import requests
import json
import time
import os
import webbrowser
import re
import emoji
import ssl
import fileinput
import sys
import random
import threading
import pygame
import configparser
import tkinter.messagebox
from tkinter import *
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from requests.packages.urllib3.exceptions import InsecureRequestWarning

ssl._create_default_https_context = ssl._create_unverified_context

ssl._create_default_https_context = ssl._create_unverified_context


__headers_web = {
    'accept': '*/*',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7',
    'Connection': 'keep-alive',
    'Content-Type': 'application/json',
    'Host': 'live.kuaishou.com',
    'Origin': 'https://live.kuaishou.com',
    'Sec-Fetch-Mode': 'cors',
    'Sec-Fetch-Site': 'same-origin',
    # User-Agent/Cookie 根据自己的电脑修改
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36',
    'Cookie': ''
}
__headers_mobile = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',#'*/*',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Connection': 'keep-alive',#'close',
    'Host': 'v.kuaishou.com',
    'Sec-Fetch-Dest': 'document',
    'Sec-Fetch-Mode': 'navigate',
    'Sec-Fetch-Site': 'none',
    'Upgrade-Insecure-Requests': '1',
    'User-Agent': '',
    'Cookie': ''
}
__headers_Requests_web = {
    'accept': '*/*',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7',
    'Connection': 'keep-alive',
    'Host': 'v.kuaishou.com',
    'Upgrade-Insecure-Requests': '1',
    # User-Agent/Cookie 根据自己的电脑修改
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36',
    'Cookie': ''
}
HEADERS = {
    'accept-encoding': 'gzip, deflate, br',
    'accept-language': 'zh-CN,zh;q=0.9',
    'pragma': 'no-cache',
    'cache-control': 'no-cache',
    'upgrade-insecure-requests': '1',
    'user-agent': "",
}
# User-Agent': 'Mozilla/5.0 (Linux; U; Android 8.1.0; zh-cn; BLA-AL00 Build/HUAWEIBLA-AL00) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.132 MQQBrowser/8.9 Mobile Safari/537.36

class QJ:
    _id = ""
    yanshi = 0
    exists = 0
    stop = False
    userid_cook = ""
    sid_cook = ""
    current_uid = ""
    video_num = 0
    uid_jici = 0
    yzm_num = 0
    ua_list_ = ""
    bak_uid = ""
    find_url1_last = ""
    find_url2_last = ""
    find_url3_last = ""
    cookie_mobile = ""
    duanlian = ""
    duanlian_list = []
    uid_list_num = 0
    zhuangtaima = ""
    dkkm = ""
    jiqima = ""
    jiance_uid = 0
    uid_list_zongshu_bak = 0
    __doufu_list_jiance = []
    doufu_list__ = []
    bakuid = ""
    bakname = ""
    cookie1 = ""
    cookie2 = ""
    cookie3 = ""
    cookie4 = ""
    cookie5 = ""
    mdl = 0




ua_list = ['Mozilla/5.0 (BB10; Touch) AppleWebKit/537.10+ (KHTML, like Gecko) Version/10.0.9.2372 Mobile Safari/537.10+','Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30','Mozilla/5.0 (Linux; U; Android 4.1; en-us; GT-N7100 Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30','Mozilla/5.0 (Linux; U; Android 4.0; en-us; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30','Mozilla/5.0 (Linux; U; Android 4.4.2; en-us; LGMS323 Build/KOT49I.MS32310c) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/83.0.4103.97 Mobile Safari/537.36','Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 550) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Mobile Safari/537.36 Edge/14.14263','Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 950) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Mobile Safari/537.36 Edge/14.14263','Mozilla/5.0 (Linux; Android 6.0.1; Moto G (4)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Mobile Safari/537.36','Mozilla/5.0 (Linux; Android 6.0.1; Nexus 10 Build/MOB31T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36','Mozilla/5.0 (PlayBook; U; RIM Tablet OS 2.1.0; en-US) AppleWebKit/536.2+ (KHTML like Gecko) Version/7.2.1.0 Safari/536.2+','Mozilla/5.0 (Linux; Android 4.4.2; Nexus 4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Mobile Safari/537.36','Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Mobile Safari/537.36','Mozilla/5.0 (Linux; Android 8.0.0; Nexus 5X Build/OPR4.170623.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Mobile Safari/537.36','Mozilla/5.0 (Linux; Android 7.1.1; Nexus 6 Build/N6F26U) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Mobile Safari/537.36','Mozilla/5.0 (Linux; Android 8.0.0; Nexus 6P Build/OPP3.170518.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Mobile Safari/537.36','Mozilla/5.0 (Linux; Android 6.0.1; Nexus 7 Build/MOB30X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36','Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 520)','Mozilla/5.0 (MeeGo; NokiaN9) AppleWebKit/534.13 (KHTML, like Gecko) NokiaBrowser/8.5.0 Mobile Safari/534.13','Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1','Mozilla/5.0 (iPhone; CPU iPhone OS 7_1_2 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Version/7.0 Mobile/11D257 Safari/9537.53','Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Mobile Safari/537.36','Mozilla/5.0 (Linux; Android 8.0; Pixel 2 Build/OPD3.170816.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Mobile Safari/537.36','Mozilla/5.0 (Linux; Android 8.0.0; Pixel 2 XL Build/OPD1.170816.004) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Mobile Safari/537.36','Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1','Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1','Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1','Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1','Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1','Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1']
__doufu_list = []

__date_cache = ""
__date_pic_count = 0

def __read_preset():
    p_path = "useid.txt"
    with open(p_path, "r") as f:
        for line in f:
            if line[0] != "#":
                QJ.doufu_list__.append(line.strip())

def doufu():
    time.sleep(1)
    __read_preset()
    latetime = int(entry.get())
    text.insert(END, "")
    text.update()
    text.see(END)
    text.insert(END, "延时时间:" + str(latetime))
    text.update()
    text.see(END)
    text.insert(END, "")
    text.update()
    text.see(END)
    text.insert(END, "准备开始爬取，共有%d个用户..." % len(QJ.doufu_list__))
    text.update()
    text.see(END)
    time.sleep(3)
    QJ.uid_list_zongshu_bak = len(QJ.doufu_list__)
    QJ.uid_jici = 0
    for uid in QJ.doufu_list__:
        if QJ.current_uid != "0":
            if uid != QJ.current_uid:
                QJ.uid_jici = QJ.uid_jici + 1
                if QJ.jiance_uid == 1:
                    uid_list_num = QJ.uid_jici + 1
                if QJ.uid_jici == len(QJ.doufu_list__):
                    QJ.uid_jici = 0
                    QJ.video_num = 0
                    break
            else:
                break
        else:
            QJ.uid_jici = 0
            QJ.video_num = 0
            break
    for uid_list_num in range(QJ.uid_jici, len(QJ.doufu_list__)):
        uid = QJ.doufu_list__[uid_list_num]
        QJ.current_uid = uid
        QJ.uid_list_num = uid_list_num
        save_config_jb2()
        QJ.bakuid = uid
        __date_cache = ""
        __date_count = 0
        if "v.douyin.com" in uid:
            QJ.ua_list_ = ua_list[random.randint(0, 28)]
            HEADERS['User-Agent'] = QJ.ua_list_
            res = requests.get(uid, headers=HEADERS, allow_redirects=False)
            if res.status_code == 302:
                long_url = res.headers['Location']
                # HEADERS['Referer'] = long_url
                # print(long_url)
                # r = requests.get(long_url)
                number = re.findall(r'sec_uid=(.*?)&utm_campaign=', long_url)
                _id = number[0]
                QJ.bak_uid = _id
                number2 = re.findall(r'share/user/(\d+)', long_url)
                _id2 = number2[0]
                QJ._id = _id2
                text.insert(END, "Short chain1:" + uid + "丨Uid:" + _id2 + "丨当前第:" + str(uid_list_num + 1) + "个用户")
                text.update()
                text.see(END)
                time.sleep(3)
                __doufu_user(_id,latetime)
                #print(QJ._id)
            else:
                text.insert(END, "请放入正确的抖音短链!!!")
                text.update()
                text.see(END)
                exit()

def __doufu_user(uid, latetime):
    # works = []
    # url = "https://www.amemv.com/share/user/%s" % uid
    # headers = HEADERS


    # print("\n获取用户名，建立文件夹中...\n")
    # response = requests.request("GET", url, headers=headers)
    # name = re.findall('<p class="nickname">(.*?)</p>', response.text)[0]
    # dir = "抖音data/" + name + "(" + uid + ")/"
    # if not os.path.exists(dir):
    #     os.makedirs(dir)
    # print("开始爬取用户 " + name + "，保存在目录 " + dir)

    page = 1
    max_cursor = 0
    res = requests.get("https://www.amemv.com/web/api/v2/aweme/post/?sec_uid=" + uid + "&count=999&max_cursor=" + str(max_cursor), headers=HEADERS)
    works = json.loads(res.content.decode(encoding='utf-8', errors='strict'))['aweme_list']
    name =  works[0]['author']['nickname']
    QJ.bakname = name
    uid_shuzi =  works[0]['author']['uid']
    dir = "抖音data/" + name + "(" + uid_shuzi + ")/"
    if not os.path.exists(dir):
        os.makedirs(dir)
    text.insert(END, "开始爬取用户 " + name + "，保存在目录 " + dir)
    text.update()
    text.see(END)
    if works != []:
        max_cursor = int(json.loads(res.content.decode(encoding='utf-8', errors='strict'))['max_cursor'])
        has_more = json.loads(res.content.decode(encoding='utf-8', errors='strict'))['has_more']
        text.insert(END, '第%s页视频地址获取成功\n' % (page))
        text.update()
        text.see(END)

        while has_more is True and max_cursor != 0:
            page += 1
            res = requests.get("https://www.amemv.com/web/api/v2/aweme/post/?sec_uid=" + uid + "&count=999&max_cursor=" + str(max_cursor), headers=HEADERS)
            works = works + json.loads(res.content.decode(encoding='utf-8', errors='strict'))['aweme_list']
            max_cursor = int(json.loads(res.content.decode(encoding='utf-8', errors='strict'))['max_cursor'])
            has_more = json.loads(res.content.decode(encoding='utf-8', errors='strict'))['has_more']
            text.insert(END, '第%s页视频地址获取成功\n' % (page))
            text.update()
            text.see(END)
        text.insert(END, "用户" + name + "共有" + str(len(works)) + "个作品")
        text.update()
        text.see(END)
        if QJ.video_num != 0:
            lum_num = QJ.video_num
            text.insert(END, "上次记录:" + "Uid or Short chain丨" + QJ.bakuid + "丨第丨" + str(
                QJ.uid_list_num + 1) + "丨个用户" + "丨第丨" + str(lum_num + 1) + "丨个视频")
            text.update()
            text.see(END)
            allnumber = 0
            text.insert(END, "")
            text.update()
            text.see(END)
        else:
            text.insert(END, "新的开始:" + "Uid or Short chain丨" + QJ.bakuid + "丨第丨" + str(
                QJ.uid_list_num + 1) + "丨个用户" + "丨第丨0丨个视频")
            text.update()
            text.see(END)
            lum_num = 0
            allnumber = 0
            text.insert(END, "")
            text.update()
            text.see(END)
        for j in range(lum_num,len(works)):
            chongxinduqu_uid()
            QJ.video_num = j
            save_config_jb2()
            if QJ.stop == True:
                text.insert(END, "成功跳过当前用户...")
                text.update()
                text.see(END)
                break
            __doufu_work(uid, dir, works[j], j + 1)
            if var.get() == 1:
                if QJ.exists == int(entry2.get()):
                    text.insert(END, "正在自动跳过当前用户...")
                    text.update()
                    text.see(END)
                    break
            time.sleep(latetime)
    text.insert(END, "用户 " + name + "视频爬取完成!")
    text.update()
    text.see(END)

    text.insert(END, "")
    text.update()
    text.see(END)
    time.sleep(1)
    text.insert(END, "等待10秒执行下一个")
    text.update()
    text.see(END)
    QJ.video_num = 0
    save_config_jb2()
    text.insert(END, "等待9秒执行下一个")
    text.update()
    text.see(END)
    time.sleep(1)
    text.insert(END, "等待8秒执行下一个")
    text.update()
    text.see(END)
    time.sleep(1)
    text.insert(END, "等待7秒执行下一个")
    text.update()
    text.see(END)
    time.sleep(1)
    text.insert(END, "等待6秒执行下一个")
    text.update()
    text.see(END)
    time.sleep(1)
    text.insert(END, "等待5秒执行下一个")
    text.update()
    text.see(END)
    time.sleep(1)
    text.insert(END, "等待4秒执行下一个")
    text.update()
    text.see(END)
    time.sleep(1)
    text.insert(END, "等待3秒执行下一个")
    text.update()
    text.see(END)
    time.sleep(1)
    text.insert(END, "等待2秒执行下一个")
    text.update()
    text.see(END)
    time.sleep(1)
    text.insert(END, "等待1秒执行下一个")
    text.update()
    text.see(END)
    QJ.stop = False
    time.sleep(1)
    text.insert(END, "")
    text.update()
    text.see(END)
    QJ.exists = 0

def __doufu_work(uid, dir, work, wdx):
    if work['desc'] == "":
        w_caption = "无文件名_" + str(wdx)
        w_name = "无文件名_" + str(wdx)
    else:
        w_caption = re.sub(r"\s+", " ", work['desc'])
        w_name2 = re.sub(r'[\\/:*?"<>|\r\n]+', "", w_caption)[0:24]
        emoji_str = emoji.demojize(w_name2)
        w_name = re.sub(r':(.*?):', '', emoji_str).strip()
    try:
        fabu = work['video']['dynamic_cover']['uri']
        fatime = re.findall(r'(?<=_)\d+', fabu)[0]
    except:
        fatime = '0000000000'

    w_time = time.strftime('%Y年%m月%d日%H时%M分%S秒', time.localtime(int(fatime)))
    w_aweme_id = work['aweme_id']

    w_url = work['video']['play_addr']['url_list'] [0]
    if w_url == "":
        w_url = work['video']['play_addr']['url_list'] [1]

    v_name = w_name + "_" + w_time + "_" + w_aweme_id + ".mp4"
    video = dir + v_name
    if os.path.exists(video):
        text.insert(END, "    视频 " + v_name + " 已存在 √")
        text.update()
        text.see(END)
        text.insert(END, "丨视频已存在 √丨")
        text.update()
        text.see(END)
        text.insert(END, "")
        text.update()
        text.see(END)
        QJ.exists += 1
        # print(QJ.bakuid + "图集或视频已存在出现了" + str(QJ.exists) + "次")
        yichuxiancishu["text"] = "用户:" + QJ.bakname + ",UID:" + QJ.bakuid + ",已存在出现" + str(QJ.exists) + "次"
        text.insert(END, "丨" + QJ.bakuid + "图集或视频已存在出现了" + str(QJ.exists) + "次" + "丨")
        text.update()
        text.see(END)
        text.insert(END, "")
        text.update()
        text.see(END)
    else:
        try:
            text.insert(END, "  " + str(wdx) + ")视频作品：" + w_caption)
            text.update()
            text.see(END)
        except:
            text.insert(END, "  这里似乎有点小错误，已跳过")
            text.update()
            text.see(END)

        while True:  # 一直循环，知道访问站点成功
            try:
                # 以下except都是用来捕获当requests请求出现异常时，
                # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
                requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
                response = requests.get(
                    w_url,
                    stream=True,
                    headers=HEADERS,
                    timeout=30,
                    allow_redirects=False,
                    verify=False)
                response.raise_for_status()
                # res = requests.get(w_url, headers=__headers_mobile, verify=False)
                # res.raise_for_status()
                break
            except requests.exceptions.HTTPError:
                text.insert(END, "HTTPError, 等待60秒后程序重新运行!!!")
                text.update()
                text.see(END)
                time.sleep(60)
                restart_program()
            except requests.exceptions.ConnectionError:
                text.insert(END, "ConnectionError, 等待60秒后程序重新运行!!!")
                text.update()
                text.see(END)
                time.sleep(60)
                restart_program()
            except requests.exceptions.ChunkedEncodingError:
                text.insert(END, "ChunkedEncodingError, 等待60秒后程序重新运行!!!")
                text.update()
                text.see(END)
                time.sleep(60)
                restart_program()
            except:
                text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待60秒后程序重新运行!!!")
                text.update()
                text.see(END)
                time.sleep(60)
                restart_program()

        v_url = response.headers['Location']
        if v_url:
            if not os.path.exists(video):
                while True:  # 一直循环，知道访问站点成功
                    try:
                        # 以下except都是用来捕获当requests请求出现异常时，
                        # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
                        requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
                        r = requests.get(v_url, headers=HEADERS,timeout=30,verify=False)
                        r.raise_for_status()
                        # res = requests.get(w_url, headers=__headers_mobile, verify=False)
                        # res.raise_for_status()
                        break
                    except requests.exceptions.HTTPError:
                        text.insert(END, "HTTPError, 等待60秒后程序重新运行!!!")
                        text.update()
                        text.see(END)
                        time.sleep(60)
                        restart_program()
                    except requests.exceptions.ConnectionError:
                        text.insert(END, "ConnectionError, 等待60秒后程序重新运行!!!")
                        text.update()
                        text.see(END)
                        time.sleep(60)
                        restart_program()
                    except requests.exceptions.ChunkedEncodingError:
                        text.insert(END, "ChunkedEncodingError, 等待60秒后程序重新运行!!!")
                        text.update()
                        text.see(END)
                        time.sleep(60)
                        restart_program()
                    except:
                        text.insert(END, "Unfortunitely -- An Unknow Error Happened, 等待60秒后程序重新运行!!!")
                        text.update()
                        text.see(END)
                        time.sleep(60)
                        restart_program()


                with open(video, "wb") as f:
                    f.write(r.content)
                text.insert(END, "    视频 " + v_name + " 下载成功 √")
                text.update()
                text.see(END)
                text.insert(END, "视频地址:")
                text.update()
                text.see(END)
                text.insert(END, v_url)
                text.update()
                text.see(END)
                text.insert(END, "丨视频下载成功 √丨")
                text.update()
                text.see(END)
                text.insert(END, "")
                text.update()
                text.see(END)
            else:
                text.insert(END, "    视频 " + v_name + " 已存在 √")
                text.update()
                text.see(END)
                text.insert(END, "丨视频已存在 √丨")
                text.update()
                text.see(END)
                text.insert(END, "")
                text.update()
                text.see(END)
        else:
            text.insert(END, "未找到视频-----60秒后程序自动重新运行!!!")
            text.update()
            text.see(END)
            time.sleep(60)
            restart_program()



def chongxinduqu_uid():
    QJ.__doufu_list_jiance = []
    p_path2 = "useid.txt"
    with open(p_path2, "r") as f2:
        for line2 in f2:
            if line2[0] != "#":
                QJ.__doufu_list_jiance.append(line2.strip())
    if len(QJ.__doufu_list_jiance) != QJ.uid_list_zongshu_bak:
        QJ.jiance_uid = 1
        QJ.doufu_list__ = []
        new_uid_list = tkinter.messagebox.askokcancel('提示', 'uid.txt有更新,请问是否重新获取uid列表!!!')
        if new_uid_list == True:
            doufu()


def restart_program():  # 重启程序
    if QJ.zhuangtaima != "":
        loginout()
        python = sys.executable
        os.execl(python, python, *sys.argv)
    else:
        python = sys.executable
        os.execl(python, python, *sys.argv)


def thread_it(func, *args):
    '''将函数打包进线程'''
    # 创建
    t = threading.Thread(target=func, args=args)
    # 守护 !!!
    t.setDaemon(True)
    # 启动
    t.start()
    # 阻塞--卡死界面！
    # t.join()


def stop():
    """Stop scanning by setting the global flag to False."""
    QJ.stop = True
    text.insert(END, "正在跳过当前用户...")
    text.update()
    text.see(END)

def save_config_jb():
    config = configparser.ConfigParser()
    config.read('.\\config.ini')
    if config.has_section('基本设置') == False:
        config.add_section('基本设置')


    config.set('基本设置','自动模式',str(var2.get()))
    config.set('基本设置','延时',entry.get())
    config.set('基本设置', '已存在次数', entry2.get())
    config.set('基本设置', '自动跳过', str(var.get()))


    o = open('.\\config.ini', 'w')
    config.write(o)
    o.close()  # 不要忘记关闭
    tkinter.messagebox.showinfo('提示', '保存配置后软件自动重启!!!')
    time.sleep(1)
    restart_program()


def save_config_jb2():
    config = configparser.ConfigParser()
    config.read('.\\config.ini')
    if config.has_section('用户日志') == False:
        config.add_section('用户日志')

    config.set('用户日志', '当前uid', QJ.current_uid)
    config.set('用户日志', '当前解析视频数', str(QJ.video_num))

    o = open('.\\config.ini', 'w')
    config.write(o)
    o.close()  # 不要忘记关闭


def save_config_jb3():
    config = configparser.ConfigParser()
    config.read('.\\config.ini')
    if config.has_section('用户日志') == False:
        config.add_section('用户日志')

    config.set('用户日志', '当前uid', "0")
    config.set('用户日志', '当前解析视频数', "0")

    o = open('.\\config.ini', 'w')
    config.write(o)
    o.close()  # 不要忘记关闭
    tkinter.messagebox.showinfo('提示', '保存配置后软件自动重启!!!')
    time.sleep(1)
    restart_program()

def save_config_jb4():
    config = configparser.ConfigParser()
    config.read('.\\config.ini')
    if config.has_section('用户日志') == False:
        config.add_section('用户日志')

    config.set('用户日志', '当前解析视频数', "0")

    o = open('.\\config.ini', 'w')
    config.write(o)
    o.close()  # 不要忘记关闭
    tkinter.messagebox.showinfo('提示', '保存配置后软件自动重启!!!')
    time.sleep(1)
    restart_program()



def on_closing():
    if messagebox.askokcancel("提示", "是否要退出软件?"):
        root.quit()


root = Tk()   #生成一个主窗口对象
root.title('奥利给丶抖音批量下载助手V1.0 正式版(暂时稳定)') #标题
width = 579
height = 710
screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth-width)/2, (screenheight-height)/2)
root.geometry(alignstr)
root.resizable(width=False, height=True)
#root.geometry('672x822+600+100') #大小位置
root.protocol('WM_DELETE_WINDOW', on_closing)
#webbrowser.open_new_tab("http://zanzhu.xiaobb.club/")

# if not os.path.exists('.\\config.ini'):
#     open('.\\config.ini', "w")
# if not os.path.getsize('.\\config.ini'):
#     config = configparser.ConfigParser()
#     config.read('.\\config.ini')
#     if config.has_section('基本设置') == False:
#         config.add_section('基本设置')
#         config.set('基本设置', '自动模式', '0')
#         config.set('基本设置', '延时', '1')
#         config.set('基本设置', '已存在次数', '20')
#         config.set('基本设置', '自动跳过', '0')
#         config.set('基本设置', '验证码出现次数', '20')
#         config.set('基本设置', '只下载图集', '0')
#         config.set('基本设置', '浏览器最大化', '0')
#         config.set('基本设置', '使用QQ登录', '0')
#         config.set('基本设置', '分享的短链', '')
#
#     if config.has_section('用户日志') == False:
#         config.add_section('用户日志')
#         config.set('用户日志', '当前uid', "0")
#         config.set('用户日志', '当前解析视频数', "0")
#     o = open('.\\config.ini', 'w')
#     config.write(o)
#     o.close()  # 不要忘记关闭

#-------------------------------------分割线

config = configparser.ConfigParser()
config.read('.\\config.ini')

# print('sections:', ' ', config.sections())
#
# # -options(section)得到该section的所有option
# print('options:', ' ', config.options('config'))
#
# # -items（section）得到该section的所有键值对
# print('items:', ' ', config.items('cmd'))
#
# # -get(section,option)得到section中option的值，返回为string类型
# print('get:', ' ', config.get('cmd', 'startserver'))
#
# # -getint(section,option)得到section中的option的值，返回为int类型
# print('getint:', ' ', config.getint('cmd', 'id'))
# print('getfloat:', ' ', config.getfloat('cmd', 'weight'))
# print('getboolean:', '  ', config.getboolean('cmd', 'isChoice'))
# """
# 首先得到配置文件的所有分组，然后根据分组逐一展示所有
# """
#
# for sections in config.sections():
#     for items in config.items(sections):
#         print(items)

config.items('基本设置')




text = Listbox(root,width=82,height=33)
text.grid(row=0,columnspan=3, sticky=W)



var2 = IntVar()
Checkbutton2 = Checkbutton(root,text="自动模式",  variable=var2)
Checkbutton2.place(x=15,y=615)
if config.getint('基本设置', '自动模式') == 1:
    Checkbutton2.select()
    thread_it(doufu, )


button5=Button(root,text="保存配置",width=10,command=lambda :thread_it(save_config_jb, ))
button5.place(x=385,y=675)

button6=Button(root,text="视频从新开始",width=10,command=lambda :thread_it(save_config_jb4, ))
button6.place(x=285,y=645)

button7=Button(root,text="全部重新开始",width=10,command=lambda :thread_it(save_config_jb3, ))
button7.place(x=285,y=675)

label = Label(root,text='延时时间:')
label.place(x=15,y=647)

entry = Entry(root,width=10)
entry.place(x=75,y=647)
entry.insert(0,config.get('基本设置', '延时'))



yichuxiancishu = Label(root, text='已出现次数')
yichuxiancishu.place(x=180,y=615)

label2 = Label(root,text='出现次数:')
label2.place(x=15,y=677)

entry2 = Entry(root,width=10)
entry2.place(x=75,y=677)
entry2.insert(0,config.get('基本设置', '已存在次数'))

var = IntVar()
Checkbutton = Checkbutton(root,text="自动跳过当前",  variable=var)
Checkbutton.place(x=175,y=675)
if config.getint('基本设置', '自动跳过') == 1:
    Checkbutton.select()

#读取用户log配置保存到class全局变量
QJ.current_uid = config.get('用户日志', '当前uid')
QJ.video_num = int(config.get('用户日志', '当前解析视频数'))

button4=Button(root,text="一键跳过当前",width=10,command=lambda :thread_it(stop, ))
button4.place(x=180,y=645)

button1=Button(root,text="开始",width=10,command=lambda :thread_it(doufu, ))
button1.place(x=485,y=645)

button2=Button(root,text="退出",width=10,command=on_closing)
button2.place(x=485,y=675)

root.mainloop()
